package com.spring.utils.api_v4.service.impl;

import com.spring.utils.api_v4.dao.*;
import com.spring.utils.api_v4.pojo.DeptInfo;
import com.spring.utils.api_v4.pojo.Password;
import com.spring.utils.api_v4.pojo.Role;
import com.spring.utils.api_v4.pojo.UserInfo;
import com.spring.utils.api_v4.pojo.response.BizException;
import com.spring.utils.api_v4.pojo.response.ResultCode;
import com.spring.utils.api_v4.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class UserService implements IUserService {
    @Autowired private IUserDao userDao;
    @Autowired private IPwdDao pwdDao;
    @Autowired private IRoleDao roleDao;


    @Override
    public Optional<UserInfo> checkLogin(String username, String password) {
        // 获取用户信息
        Optional<UserInfo> op = userDao.findByPhone(username);
        if(op.isPresent()) {
            // 获取密码信息
            Password pwd = pwdDao.findByUserInfo(op.get());
            // 如果密码不存在，则初始化密码
            if(pwd == null) {
                pwd = initUserPwd(op.get());
            }
            if(pwd.getPassword().equals(password)) {
                return op;
            }
        }
        return Optional.empty();
    }

    @Override
    public Role addUserRole(String userId, String name) {
        Optional<UserInfo> op = userDao.findById(userId);
        if(op.isEmpty()) {
            throw new BizException(ResultCode.USER_NOT_EXIST);
        }
        if(roleDao.existsByUserInfoAndName(op.get(), name)) {
            throw new BizException(ResultCode.ROLE_EXIST);
        }
        Role role = new Role();
        role.setUserInfo(op.get());
        role.setName(name);
        roleDao.save(role);
        return role;
    }

    /**
     * 初始化用户密码
     * @param userInfo
     */
    private Password initUserPwd(UserInfo userInfo) {
        pwdDao.deleteByUserInfo(userInfo);
        Password pwd = new Password();
        pwd.setUserInfo(userInfo);
        pwd.setPassword(userInfo.getIdCard().substring(12));
        pwdDao.save(pwd);
        return pwd;
    }
}
